<template>
  <div class="home-container">
  <!-- 加载状态 -->
  <div v-if="cartStore.loading" class="loading-overlay">
    <div class="loading-spinner">加载中...</div>
  </div>

  <!-- 顶部导航 -->
  <div class="header">
    <div class="header-inner">
      <div class="logo">
        <img src="@/assets/Logo.png" alt="鲸选Logo" />
      </div>
      <div class="nav-links">
        <router-link to="/home" class="nav-item">首页</router-link>
        <router-link to="/personalcenter" class="nav-item">个人中心</router-link>
      </div>
      <div class="search-bar" @click.stop>
        <input v-model="searchQuery" type="text" placeholder="搜索购物车内的商品" @focus="showHistory = true" />
        <div v-show="showHistory" class="search-history-dropdown">
          <template v-if="searchHistory.length > 0">
            <div v-for="(term, i) in searchHistory" :key="i" class="search-history-item" @click="selectHistory(term)">
              {{ term }}
            </div>
            <div class="search-history-item clear-history" @click="clearHistory">
              🗑️ 清空历史记录
            </div>
          </template>
          <div v-else class="search-history-item no-record">
            暂无搜索记录
          </div>
        </div>
      </div>
      <div class="category-select" @click.stop="toggleCategory">
        <span>{{ selectedCategory || '分类' }}</span>
        <div v-show="showCategory" class="category-dropdown">
          <div v-for="(item, index) in categories" :key="index" class="category-item"
            :class="{ active: selectedCategory === item }" @click="selectCategory(item)">
            {{ item }}
          </div>
        </div>
      </div>
      <div class="header-right">
        <button class="action-btn" :disabled="!hasSelected" @click="handleDelete">
          删除 ({{ cartStore.selectedItems.length }})
        </button>
        <button class="action-btn" style="margin-right: 10px;" @click="handleClearCart">
          清空购物车
        </button>
      </div>
    </div>
  </div>

  <!-- 购物车商品列表 -->
  <div class="cart-list">
    <!-- 全选 -->
    <div class="cart-header">
      <label class="select-all">
        <input type="checkbox" :checked="isAllSelected" @change="handleToggleSelectAll" />
        全选 ({{ cartStore.selectedItems.length }}/{{ cartStore.items.length }})
      </label>
      <div class="cart-summary">
        <span>总计: ¥{{ cartStore.totalPrice.toFixed(2) }}</span>
      </div>
    </div>

    <!-- 空购物车提示 -->
    <div v-if="cartStore.items.length === 0" class="empty-cart">
      <p>购物车是空的</p>
      <button class="btn" @click="goToHomePage">去购物</button>
    </div>

    <!-- 商品列表 -->
    <div v-for="item in filteredProducts" :key="item.productId" class="cart-item">
      <!-- 商品复选框 -->
      <div class="item-checkbox">
        <input type="checkbox" :checked="item.selected" @change="handleToggleSelect(item.productId, $event)" />
      </div>

      <div class="item-image">
        <img :src="item.imageUrl || 'data:image/svg+xml,%3Csvg...'" :alt="item.productName" />
      </div>
      <div class="item-info">
        <div class="item-title">{{ item.productName }}</div>
        <div class="item-price">¥{{ item.unitPrice }}</div>
        <div class="item-desc">数量: {{ item.quantity }}</div>
        <div class="item-purchase">小计: ¥{{ item.amount.toFixed(2) }}</div>
      </div>
      <div class="item-actions">
        <div class="quantity-controls">
          <button class="quantity-btn" @click="handleDecreaseQuantity(item)" :disabled="item.quantity <= 1">-</button>
          <input type="number" :value="item.quantity" @change="handleQuantityChange(item, $event)" min="1" max="999" class="quantity-input" />
          <button class="quantity-btn" @click="handleIncreaseQuantity(item)">+</button>
        </div>
        <button class="action-btn buy-btn" @click="handleBuyNow(item)">立即购买</button>
        <button class="action-btn delete-btn" @click="handleRemoveItem(item.productId)">删除</button>
      </div>
    </div>
  </div>
  </div>

</template>

<script setup>
import { ref, onMounted, computed, onUnmounted, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useCartStore } from '@/stores/cart'
import { getProductDetail } from '@/api/index'

const isSuccess = (res) => res && (res.code === 0 || res.code === 200)

const router = useRouter()
const cartStore = useCartStore()

// ========== 分类下拉 ==========
const categories = ['类别1', '类别2', '重置']
const showCategory = ref(false)
const selectedCategory = ref(null)

const toggleCategory = () => {
  showCategory.value = !showCategory.value
}

const selectCategory = (category) => {
  selectedCategory.value = category
  showCategory.value = false
}

// 关闭分类下拉（点击外部）
const handleClickOutsideCategory = (e) => {
  if (!e.target.closest('.category-select')) {
    showCategory.value = false
  }
}

// ========== 搜索历史 ==========
const searchQuery = ref('')
const showHistory = ref(false)
const searchHistory = ref([])
const HISTORY_KEY = 'cartSearchHistory'

const loadSearchHistory = () => {
  const history = JSON.parse(localStorage.getItem(HISTORY_KEY) || '[]')
  searchHistory.value = history
}

const selectHistory = (term) => {
  searchQuery.value = term
  showHistory.value = false
}

const clearHistory = () => {
  localStorage.removeItem(HISTORY_KEY)
  searchHistory.value = []
  searchQuery.value = ''
}

// ========== 商品数据增强 ==========
const productDetails = ref({})

// 获取商品详情并缓存
const fetchProductDetails = async (productId) => {
  if (productDetails.value[productId]) {
    return productDetails.value[productId]
  }
  
  try {
    const res = await getProductDetail(productId)
    if (isSuccess(res)) {
      productDetails.value[productId] = res.data
      return res.data
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
  }
  return null
}

// 获取增强的商品列表（包含商品详情）
const enhancedProducts = computed(() => {
  return cartStore.items.map(item => {
    const detail = productDetails.value[item.productId]
    return {
      ...item,
      productName: detail?.productName || `商品 ${item.productId}`,
      imageUrl: detail?.imageUrl || '',
      platformName: detail?.platformName || ''
    }
  })
})

// 根据搜索和分类过滤商品
const filteredProducts = computed(() => {
  let result = enhancedProducts.value

  // 搜索过滤
  if (searchQuery.value.trim()) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(item => 
      item.productName.toLowerCase().includes(query) ||
      item.productId.toString().includes(query)
    )
  }

  // 分类过滤（待实现）
  // if (selectedCategory.value && selectedCategory.value !== '重置') {
  //   result = result.filter(item => item.category === selectedCategory.value)
  // }

  return result
})

// 判断是否有选中项
const hasSelected = computed(() => cartStore.selectedItems.length > 0)

// 判断是否全选
const isAllSelected = computed(() => {
  if (cartStore.items.length === 0) return false
  return cartStore.items.every(item => item.selected === true)
})

// ========== 商品操作 ==========

// 切换单个商品选中状态
const handleToggleSelect = async (productId, event) => {
  const selected = event.target.checked
  await cartStore.toggleSelection(productId, selected)
}

// 全选 / 取消全选
const handleToggleSelectAll = async () => {
  const selected = !isAllSelected.value
  await cartStore.toggleSelectAll(selected)
}

// 增加数量
const handleIncreaseQuantity = async (item) => {
  await cartStore.updateQuantity(item.productId, item.quantity + 1)
}

// 减少数量
const handleDecreaseQuantity = async (item) => {
  if (item.quantity > 1) {
    await cartStore.updateQuantity(item.productId, item.quantity - 1)
  }
}

// 手动输入数量
const handleQuantityChange = async (item, event) => {
  let newQuantity = parseInt(event.target.value)
  
  // 验证输入
  if (isNaN(newQuantity) || newQuantity < 1) {
    newQuantity = 1
  } else if (newQuantity > 999) {
    newQuantity = 999
  }
  
  // 只有数量真正改变时才更新
  if (newQuantity !== item.quantity) {
    const success = await cartStore.updateQuantity(item.productId, newQuantity)
    // 如果更新失败，恢复输入框的值为当前商品的实际数量
    if (!success) {
      // 使用 nextTick 确保 DOM 更新后再设置值
      await nextTick()
      event.target.value = cartStore.items.find(i => i.productId === item.productId)?.quantity || item.quantity
    }
  } else {
    // 如果输入的值无效，恢复原值
    event.target.value = item.quantity
  }
}

// 删除单个商品
const handleRemoveItem = async (productId) => {
  if (confirm('确定要删除该商品吗？')) {
    const success = await cartStore.removeItem(productId)
    if (!success && cartStore.error) {
      alert(`删除失败: ${cartStore.error}`)
    }
  }
}

// 删除所有选中项
const handleDelete = async () => {
  if (!hasSelected.value) {
    alert('请先选择要删除的商品')
    return
  }
  
  const count = cartStore.selectedItems.length
  if (confirm(`确定删除 ${count} 件商品？`)) {
    const success = await cartStore.removeSelectedItems()
    if (success) {
      alert(`成功删除 ${count} 件商品`)
    } else {
      alert('删除失败，请重试')
    }
  }
}

// 清空购物车
const handleClearCart = async () => {
  if (cartStore.items.length === 0) {
    alert('购物车已经是空的了')
    return
  }
  
  if (confirm(`确定要清空购物车吗？将删除 ${cartStore.items.length} 件商品`)) {
    const success = await cartStore.clearAll()
    if (success) {
      alert('购物车已清空')
    } else {
      alert('清空失败，请重试')
    }
  }
}

const handleBuyNow = async (item) => {
  // 获取商品详情以获取link字段
  const productDetail = await fetchProductDetails(item.productId)
  console.log('商品详情:', productDetail) // 添加调试信息
  
  if (productDetail) {
    // 尝试多种可能的链接字段名
    const link = productDetail.link || productDetail.url || productDetail.productUrl || productDetail.purchaseUrl
    
    if (link) {
      // 打开商品链接到新窗口
      window.open(link, '_blank')
    } else {
      alert('获取商品详情失败，请稍后重试')
    }
  } else {
    alert('获取商品详情失败，请稍后重试')
  }
}

const goToHomePage = () => {
  router.push('/home')
}

// 监听购物车变化，自动获取商品详情
const fetchMissingProductDetails = async () => {
  const promises = cartStore.items
    .filter(item => !productDetails.value[item.productId])
    .map(item => fetchProductDetails(item.productId))
  await Promise.all(promises)
}

// 监听购物车商品变化，自动获取新商品详情
watch(() => cartStore.items.length, async () => {
  await fetchMissingProductDetails()
})

// ========== 生命周期 ==========
onMounted(async () => {
  // 加载搜索历史
  loadSearchHistory()

  // 从后端获取购物车数据
  await cartStore.fetchCartItems()

  // 获取所有商品详情
  await fetchMissingProductDetails()

  // 全局点击监听
  document.addEventListener('click', handleClickOutsideCategory)

  // 搜索历史外部点击关闭
  const handleSearchOutside = (e) => {
    if (!e.target.closest('.search-bar')) {
      showHistory.value = false
    }
  }
  document.addEventListener('click', handleSearchOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutsideCategory)
})
</script>

<style>
body {
  font-family: 'Microsoft YaHei', sans-serif;
  background-color: #f5f5f5;
  margin: 0;
  padding: 0;
  min-height: 100vh;
}
</style>

<style scoped>
@import '@/CSS/ShoppingCart.css';
</style>
